<template>
  <div class="demo">
    <el-card>
      <div slot="header">
        <span>API请求示例</span>
      </div>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-button type="primary" @click="testGet" :loading="loading.get">
            测试GET请求
          </el-button>
          <el-button type="success" @click="testPost" :loading="loading.post">
            测试POST请求
          </el-button>
          <el-button type="warning" @click="testError">
            测试错误处理
          </el-button>
        </el-col>
      </el-row>
      
      <el-divider></el-divider>
      
      <div v-if="responseData">
        <h4>响应数据：</h4>
        <el-input
          type="textarea"
          :rows="10"
          :value="JSON.stringify(responseData, null, 2)"
          readonly
        ></el-input>
      </div>
    </el-card>
  </div>
</template>

<script>
import { commonApi } from '../api'

export default {
  name: 'Demo',
  data() {
    return {
      loading: {
        get: false,
        post: false
      },
      responseData: null
    }
  },
  methods: {
    async testGet() {
      this.loading.get = true
      try {
        // 这里使用一个公开的测试API
        const response = await commonApi.get('https://jsonplaceholder.typicode.com/posts/1')
        this.responseData = response
        this.$message.success('GET请求成功')
      } catch (error) {
        console.error('GET请求失败:', error)
      } finally {
        this.loading.get = false
      }
    },
    
    async testPost() {
      this.loading.post = true
      try {
        const response = await commonApi.post('https://jsonplaceholder.typicode.com/posts', {
          title: 'foo',
          body: 'bar',
          userId: 1
        })
        this.responseData = response
        this.$message.success('POST请求成功')
      } catch (error) {
        console.error('POST请求失败:', error)
      } finally {
        this.loading.post = false
      }
    },
    
    async testError() {
      try {
        await commonApi.get('https://jsonplaceholder.typicode.com/posts/999999')
      } catch (error) {
        // 错误已经在拦截器中处理
        console.error('请求失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.demo {
  max-width: 1200px;
  margin: 0 auto;
}
</style>